package com.study.h190808viewpagerstudy.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.CornerPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.widget.LinearLayout;

/**
 * 项目名: H190808ViewPagerStudy
 * 包 名:  com.study.h190808viewpagerstudy.view
 * 文件名: ViewPagerIndicator
 * 创建者: hw2019
 * 时 间:  2019-08-08 11:52
 * 描 述:  商品详情界面的顶部指示器
 */

public class ViewPagerIndicator extends LinearLayout {

    //Note：绘制三角形指示器所需要的变量
    private Paint mPaint;
    private Path mPath;

    private int mTriangleWidth;
    private int mTriangleHeight;

    private static final float RADIO_TRIANGLE_WIDTH = 1/6F;
    private int mInitTranslationX, mTranslationX;

    /**
     * Note: 构造方法
     * @param context
     */
    public ViewPagerIndicator(Context context) {
        this(context, null);
    }

    /**
     * Note: 构造方法
     * @param context
     */
    public ViewPagerIndicator(Context context, AttributeSet attrs) {
        super(context, attrs);

        // Note: 初始化画笔
        mPaint = new Paint();
        //设置抗锯齿
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.parseColor("#ffffffff"));
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setPathEffect(new CornerPathEffect(3));
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {

        canvas.save();
        canvas.translate(mInitTranslationX + mTranslationX, getHeight() + 2);
        canvas.drawPath(mPath, mPaint);
        canvas.restore();

        super.dispatchDraw(canvas);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        mTriangleWidth = (int) (w / 3 * RADIO_TRIANGLE_WIDTH);
        mInitTranslationX = w / 3 / 2  - mTriangleWidth / 2;
        initTrangle();
    }

    /**
     * Note: 初始化三角形
     */
    private void initTrangle() {
        mTriangleHeight = mTriangleWidth / 2;

        mPath = new Path();
        mPath.moveTo(0, 0 );
        mPath.lineTo(mTriangleWidth, 0);
        mPath.lineTo(mTriangleWidth / 2, -mTriangleHeight);
        mPath.close();
    }

    /**
     * Note: 指示器滚动方法
     * @param position
     * @param positionOffset
     */
    public void scroll(int position, float positionOffset) {

        int tabWidth = getWidth() / 3;
        mTranslationX = (int) (tabWidth * (positionOffset + position));

        invalidate();
    }
}
